package database

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	"github.com/star-find-cloud/star-chat/conf"
	log "github.com/star-find-cloud/star-chat/pkg/logger"
	"sync"

	_ "github.com/jackc/pgx/v5/stdlib"
)

type PgSQL struct {
	_db *sqlx.DB
}

var (
	pgSQL  = &PgSQL{}
	pgOnce = &sync.Once{}
)

func initPgSQL() (*sqlx.DB, error) {
	var (
		_db *sqlx.DB
		err error
	)
	pgOnce.Do(func() {
		c := conf.GetConfig()
		host := c.Database.PgSQL.Host
		port := c.Database.PgSQL.Port
		user := c.Database.PgSQL.User
		password := c.Database.PgSQL.Password
		dbName := c.Database.PgSQL.DBName
		schema := c.Database.PgSQL.Schema
		dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable search_path=%s", host, port, user, password, dbName, schema)
		_db, err = sqlx.Connect("pgx", dsn)
		if err != nil {
			log.SQLLogger.Errorf("connect pg database failed, err:%v\n", err)
		} else {
			log.SQLLogger.Info("connect pg database success")
		}

		_db.SetMaxOpenConns(c.Database.PgSQL.MaxOpenConns)
		_db.SetMaxIdleConns(c.Database.PgSQL.MaxIdleConns)
	})
	return _db, err
}

func NewPgSQL() *PgSQL {
	db, err := initPgSQL()
	if err != nil {
		log.SQLLogger.Errorf("init pg database failed, err:%v", err)
	}
	pgSQL._db = db
	return pgSQL
}

func (p *PgSQL) GetDB() *sqlx.DB {
	return p._db
}

func (p *PgSQL) Ping() error {
	return p._db.Ping()
}

func (p *PgSQL) Close() error {
	return p._db.Close()
}
